package org.zjx;

import org.zjx.window.window.ActivationManager;
import org.zjx.window.window.WindowManager;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

//TIP 要<b>运行</b>代码，请按 <shortcut actionId="Run"/> 或
// 点击装订区域中的 <icon src="AllIcons.Actions.Execute"/> 图标。
public class Main {

    /**
     * 目标窗口数量
     */
    private static final int TARGET_WINDOW_COUNT = 1;

    /**
     * 游戏可执行文件路径
     */
    private static final String GAME_EXE_PATH = "D:\\OneDrive\\桌面\\梦幻西游.lnk";

    public static void main(String[] args) {
        System.out.println("程序开始启动...");
        System.out.println("目标窗口数量: " + TARGET_WINDOW_COUNT);
        System.out.println("游戏路径: " + GAME_EXE_PATH);

        WindowManager windowManager = null;
        try {
            // 创建窗口管理器
            windowManager = new WindowManager(TARGET_WINDOW_COUNT, GAME_EXE_PATH);

            // 添加关闭钩子，确保优雅关闭
            WindowManager finalWindowManager = windowManager;
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                System.out.println("正在关闭程序...");
                finalWindowManager.stop();
                ActivationManager.shutdown();
                System.out.println("程序已关闭");
            }));

            // 启动窗口管理器
            System.out.println("启动窗口管理器...");
            windowManager.start();

            // 程序运行中...
            System.out.println("程序运行中，按回车键退出...");

            // 使用 CountDownLatch 保持主线程运行
            CountDownLatch keepAliveLatch = new CountDownLatch(1);

            // 添加控制台监听，按回车退出
            new Thread(() -> {
                try {
                    System.in.read();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                keepAliveLatch.countDown();
            }).start();

            keepAliveLatch.await(); // 阻塞直到收到回车信号

        } catch (Exception e) {
            System.err.println("程序异常: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 优雅关闭
            System.out.println("正在关闭程序...");
            if (windowManager != null) {
                windowManager.stop();
            }
            ActivationManager.shutdown();
            System.out.println("程序正常结束");
        }
    }
}